<template>
  <div v-if="!loading" class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-8 py-8">
      <!-- 头部歌曲信息 -->
      <div class="flex gap-8 mb-10">
        <div class="shrink-0">
          <img
            :src="songInfo.coverUrl"
            alt="歌曲封面"
            class="w-48 h-48 object-cover rounded-lg"
          />
        </div>
        <div class="flex-1">
          <h1 class="text-2xl font-bold">{{ songInfo.title }}</h1>
          <div class="mt-4 flex items-center gap-2">
            <button
              @click="handlePlay"
              class="flex items-center gap-2 px-4 h-8 bg-[#dedede] text-gray-900 rounded hover:bg-gray-300"
            >
              <IconPlay class="w-5 h-5" />
              <span>播放</span>
            </button>
            <button
              @click="handleCollect"
              class="flex items-center px-2 py-2 h-8 bg-[#dedede] rounded text-red-500"
            >
              <IconHeart class="w-5 h-5" v-if="!isCollected" />
              <IconHeartFilled class="w-5 h-5" v-else />
            </button>
            <!-- <div class="flex flex-col items-start">
              <span class="text-xs text-gray-600">播放次数</span>
              <span class="text-2xl font-bold text-gray-800">{{
                songInfo.playCount
              }}</span>
            </div> -->
          </div>
          <p class="text-sm text-gray-500 mt-2">
            发行于 {{ songInfo.releaseDate }}
          </p>
          <p class="mt-4 text-gray-600">歌手：{{ songInfo.artist }}</p>
          <p class="mt-2 text-gray-600">专辑：{{ songInfo.album }}</p>
        </div>
      </div>

      <!-- 歌词展示 -->
      <div class="mt-8">
        <h2 class="text-xl font-bold mb-6">歌词</h2>
        <div class="whitespace-pre-line text-gray-600">
          {{ songInfo.lyrics }}
        </div>
      </div>

      <!-- 评论区 -->
      <div class="mt-12">
        <CommentSection
          :comments="comments"
          :music-id="songId"
          @comment-added="refreshComments"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { IconPlay, IconHeart, IconHeartFilled } from "@/components/icons";
import CommentSection from "@/components/CommentSection.vue";
import { useSongAPI } from "@/services/song";
import { useCommentAPI } from "@/services/comment";
import { useUserStore } from "@/stores/user";
import { usePlayerStore } from "@/stores/player";
import { ElMessage } from "element-plus";

const route = useRoute();
const songAPI = useSongAPI();
const commentAPI = useCommentAPI();
const userStore = useUserStore();
const playerStore = usePlayerStore();

const songInfo = ref({
  id: Number(route.params.id),
  title: "",
  coverUrl: "",
  artist: "",
  album: "",
  playCount: 0,
  releaseDate: "",
  lyrics: "",
  url: "", // 添加 url 字段
});

const comments = ref([]);
const loading = ref(true);
const songId = route.params.id as string;
const isCollected = ref(false);

// 刷新评论列表
const refreshComments = async () => {
  try {
    const { data } = await commentAPI.getCommentByMusicId(songId);
    if (data) {
      comments.value = data;
    }
  } catch (error) {
    console.error("获取评论失败:", error);
  }
};

// 检查收藏状态
const checkCollectionStatus = async () => {
  if (userStore.isLogin) {
    try {
      const response = await songAPI.checkSongFavorStatus(
        userStore.uid,
        songId
      );
      console.log(response);

      if (response.data) {
        if (response.data == 1) {
          isCollected.value = true;
        } else {
          isCollected.value = false;
        }
      }
    } catch (error) {
      console.error("获取收藏状态失败:", error);
    }
  }
};

// 处理收藏/取消收藏
const handleCollect = async () => {
  if (!userStore.isLogin) {
    ElMessage.warning("请先登录");
    return;
  }

  const originalState = isCollected.value;
  isCollected.value = !isCollected.value;

  try {
    const res = originalState
      ? await songAPI.getCancelCollectSong(songId, userStore.uid)
      : await songAPI.getCollectSong(songId, userStore.uid);

    if (res.code === 200) {
      ElMessage.success(originalState ? "已取消收藏" : "收藏成功");
    } else {
      isCollected.value = originalState;
      ElMessage.error(originalState ? "取消收藏失败" : "收藏失败");
    }
  } catch (error) {
    isCollected.value = originalState;
    ElMessage.error(originalState ? "取消收藏失败" : "收藏失败");
    console.error("操作失败:", error);
  }
};

// 修改播放处理函数
const handlePlay = () => {
  const song = {
    id: songInfo.value.id,
    name: songInfo.value.title,
    artist: songInfo.value.artist,
    url: songInfo.value.url,
    cover: songInfo.value.coverUrl,
    lyric: songInfo.value.lyrics,
  };
  playerStore.playSong(song);
};

const formatLyrics = (lyrics: string) => {
  if (!lyrics) return "暂无歌词";
  // 移除时间标签和元数据标签
  return lyrics
    .split("\n")
    .filter((line) => line.trim()) // 移除空行
    .map((line) => {
      // 如果行以[开头且包含]，则移除这部分内容
      if (line.startsWith("[") && line.includes("]")) {
        const content = line.split("]")[1];
        return content || "";
      }
      return line;
    })
    .filter((line) => line) // 移除空行
    .join("\n");
};

onMounted(async () => {
  try {
    loading.value = true;
    const [songResponse, commentResponse] = await Promise.all([
      songAPI.getSongDetail(songId),
      commentAPI.getCommentByMusicId(songId),
    ]);

    if (songResponse.data) {
      songInfo.value = {
        id: songResponse.data.musicId,
        title: songResponse.data.musicName,
        coverUrl: songResponse.data.musicCoverUrl,
        artist: songResponse.data.musicAuthor,
        album: songResponse.data.album || "未知专辑",
        playCount: songResponse.data.playCount || 0,
        releaseDate: songResponse.data.releaseDate || "未知日期",
        lyrics: formatLyrics(songResponse.data.lyric) || "暂无歌词",
        url: songResponse.data.musicUrl, // 添加音乐 URL
      };
    }

    // 设置评论数据
    if (commentResponse.data) {
      comments.value = commentResponse.data;
    }

    await checkCollectionStatus(); // 添加检查收藏状态
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.song-detail {
  padding: 20px;
}
</style>
